package com.lonbon.threecameramaster.test;

import static android.content.Context.WIFI_SERVICE;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_WIFI;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 创百合子相关api方法
 */
public class ApiUtils {

    //获取设备序列号
    @SuppressLint("MissingPermission")
    public static String getDeviceSN() {
        if (Build.VERSION.SDK_INT >= 29) {
            try {
                Class cls = Class
                        .forName("android.os.SystemProperties");
                Method m = cls
                        .getMethod("get",   String.class,String.class);
                String sn = (String)
                        m.invoke(cls,"ro.serialno", Build.UNKNOWN);
                return sn;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return "";
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return Build.getSerial();
        } else {
            return Build.SERIAL;
        }
    }

    //获取设备内存信息
    public static int getMemorySize(){
        //内存信息可以通过读取"/proc/meminfo"文件获得：
        int memorySizeKB=0;//单位：KB
        try {
            BufferedReader br = new BufferedReader(new
                    FileReader("/proc/meminfo"));
            String content = br.readLine();
            String[] contentes = content.split("\\s+");
            memorySizeKB = Integer.parseInt(contentes[1]);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return memorySizeKB;
    }

    //获取设备的存储容量
    public static long getTotalSize(){
        //需要android.permission.WRITE_EXTERNAL_STORAGE 权限：
        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long totalSizeB = statFs.getTotalBytes();//单位：B
        return totalSizeB;
      //  注意：这个totalSizeB不包括系统占用空间。
    }


    //获取设备固件版本
    public static String getVersion(){
        String version = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            version = (String) get.invoke(c, "ro.build.display.id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    //获取设备内核版本
    public static String getKernelVersion(){
        String kernelVersion = "";
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("/proc/version");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return kernelVersion;
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 8 * 1024);
        String info = "";
        String line = "";
        try {
            while ((line = bufferedReader.readLine()) != null) {
                info += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            if (info != "") {
                final String keyword = "version ";
                int index = info.indexOf(keyword);
                line = info.substring(index + keyword.length());
                index = line.indexOf(" ");
                kernelVersion = line.substring(0, index);
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        return kernelVersion;
    }

    //获取WIFI ip地址
    public static String getIP(Context context){
        //需要android.permission.ACCESS_WIFI_STATE权限：

        //获取wifi服务
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = (ipAddress & 0xFF) + "." + ((ipAddress >> 8) & 0xFF) + "." + ((ipAddress >> 16) & 0xFF) + "." + (ipAddress >> 24 & 0xFF);
        return ip;
    }

    //获取MAC
    public static String getMac(Context context){
        //需要android.permission.ACCESS_WIFI_STATE权限：
        // 使用WifiManager获取Mac地址
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = null;
        if (wifiManager != null) {
            wifiInfo = wifiManager.getConnectionInfo();
        }

        // 获取Mac地址
        String macAddress = null;
        if (wifiInfo != null) {
            macAddress = wifiInfo.getMacAddress();
        }
        return macAddress;
    }

    //查询以太网Mac地址
    public static String getEthernetMacAddress(){
        String ethernetMacAddress =null;
        try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream("/sys/class/net/eth0/address")))) {
            ethernetMacAddress = input.readLine();
        } catch (IOException ex) {
        }
        return ethernetMacAddress;
    }

    //获取设备的上网方式
    public static int getNetworkType(Context context){
        //需要android.permission.ACCESS_NETWORK_STATE权限：
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
        //  return activeNetworkInfo.getTypeName();
            return activeNetworkInfo.getType();
        }
        return 0;
    }


    //获取设备的上网方式
    public static String getIpAddress(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == TYPE_ETHERNET) {
                return getIpAddressForInterfaces();
            } else if (info.getType() == TYPE_WIFI) {
                return getLocalIpAddress(context);
            }
        }
        return "0.0.0.0";
    }

    //获取WIFI IP
    public static String getLocalIpAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = (ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff);
        return ip;
    }


    //获取以太网IP
    public static String getIpAddressForInterfaces() {
        String interfaceName = "eth0";
        try {
            Enumeration<NetworkInterface> enNetworkInterface = NetworkInterface.getNetworkInterfaces(); //获取本机所有的网络接口
            while (enNetworkInterface.hasMoreElements()) {  //判断 Enumeration 对象中是否还有数据
                NetworkInterface networkInterface = enNetworkInterface.nextElement();   //获取 Enumeration 对象中的下一个数据
                if (!networkInterface.isUp()) { // 判断网口是否在使用
                    continue;
                }
                if (!interfaceName.equals(networkInterface.getDisplayName())) { // 网口名称是否和需要的相同
                    continue;
                }
                Enumeration<InetAddress> enInetAddress = networkInterface.getInetAddresses();   //getInetAddresses 方法返回绑定到该网卡的所有的 IP 地址。
                while (enInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enInetAddress.nextElement();
                    if (inetAddress instanceof Inet4Address) {  //判断是否未ipv4
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0.0.0.0";
    }

    //关机
    public static void shutDown(Context context){
        context.sendBroadcast(new Intent("android.intent.action.shutdown"));
    }

    //重启
    public static void reboot(Context context){
        context.sendBroadcast(new Intent("android.intent.action.reboot"));
    }

    //设置开机时间
    public static void setPowerOnTime(long timeInMillis) {
        File root = new File("/sys/class/rtc/");
        if (root.exists()) {
            File[] rtcs = root.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File file, String s) {
                    return s.startsWith("rtc");
                }
            });

            for (File rtc: rtcs) {
                File wakealarm = new File(rtc.getAbsolutePath() + "/wakealarm");
                if (wakealarm.exists()) {
                    writeSysFile(wakealarm, "0".getBytes());
                    if (timeInMillis <= 0) {
                        continue;
                    }
                    writeSysFile(wakealarm, String.valueOf((timeInMillis + 1000 - 1) / 1000).getBytes());
                }
            }
        }
    }


    //设置关机时间
    public static void setPowerOffTime(Context context,long timeInMillis) {
        PendingIntent pi = PendingIntent.getBroadcast(context,
                0,
                new Intent("android.intent.action.shutdown"),
                PendingIntent.FLAG_IMMUTABLE);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (timeInMillis > 0) {
            am.set(AlarmManager.RTC_WAKEUP, timeInMillis, pi);
        } else {
            am.cancel(pi);
        }
    }

    //
    //1、启用静态IP设置：
    private void setEthernetStaticConfig(Context context,String ip, String netmask, String gateway, String[] dns, String proxy, String exclusion, String pac) {
        Intent intent = new Intent("com.cbest.eth.config");
        intent.putExtra("mode", "static");
        intent.putExtra("ip", ip);
        intent.putExtra("netmask", netmask);
        intent.putExtra("gateway", gateway);
        if (dns != null) {
            for (int idx = 0; idx < dns.length; idx++) {
                intent.putExtra(String.format("dns%d", idx+1),   dns[idx]);
            }
        }
        if (!TextUtils.isEmpty(proxy)) {
            intent.putExtra("proxy", proxy);
            if (!TextUtils.isEmpty(exclusion)) {
                intent.putExtra("exclusion", exclusion);
            }
        } else if (!TextUtils.isEmpty(pac)){
            intent.putExtra("pac", pac);
        }
        context.sendBroadcast(intent);
    }

    //2、启用DHCP设置：
    private void setEthernetDhcpConfig(Context context) {
        Intent intent = new Intent("com.cbest.eth.config");
        intent.putExtra("mode", "dhcp");
        context.sendBroadcast(intent);
    }

    //设置系统时间
    public static void setSysTime(long timeInMillis){
        SystemClock.setCurrentTimeMillis(timeInMillis);
    }

    //设置系统时间
    public static void setTime(Context context,long timeInMillis) {
        try {
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.setTime(timeInMillis);
            return;
        } catch (SecurityException e) {

        }

        int result = Shell.run(new String[] {"date", String.format("@%d", (timeInMillis + 1000 - 1)/1000)}, Shell.User.ROOT);
        if (result == 0) {
            Shell.run(new String[] {"hwclock", "-w"}, Shell.User.ROOT);
        }
    }

    //静默安装
    public static void install(String filePath, InstallAppListener listener) {
            String cmd = "pm install -r " + filePath;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Process p = null;
                    try {
                        p = Runtime.getRuntime().exec("su");
                        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
                        w.write(cmd);
                        w.flush();
                        w.close();
                        String infoLine = "";
                        while ((infoLine = ie.readLine()) != null) {
                            if (listener != null) {
                                listener.onError(infoLine);
                            }
                        }
                        while ((infoLine = in.readLine()) != null) {
                            if (listener != null) {
                                listener.onMessage(infoLine);
                            }
                        }
                        in.close();
                        ie.close();
                        int res = p.waitFor();
                        if (listener != null) {
                            listener.onResult(res);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    //导航栏显示或隐藏
    public static void setNavigation(Context context,boolean isHidden){
        if (isHidden){
            context.sendBroadcast(new Intent("com.cbest.hide_nav_bar"));
        } else {
            context.sendBroadcast(new Intent("com.cbest.show_nav_bar"));
        }
    }

    //状态栏显示或隐藏
    public  static void setStatusBar(Context context,boolean isHidden){
        if (isHidden){
            context.sendBroadcast(new Intent("com.cbest.hide_status_bar"));
        }else {
            context.sendBroadcast(new Intent("com.cbest.show_status_bar"));
        }
    }

    //设置背光 不能控制HDMI
    public static void setBacklightBrightness(boolean raw, int level) {
        if (level > 255) level = 255;
        if (level < 0) level = 0;

        if (raw) {
            File root = new File("/sys/class/backlight/");
            if (root.exists()) {
                File[] backlights = root.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.startsWith("backlight");
                    }
                });

                for (File backlight : backlights) {
                    File brightness = new File(backlight.getAbsolutePath() + "/brightness");
                    if (brightness.exists()) {
                        writeSysFile(brightness, String.valueOf(level).getBytes());
                    }
                }
            }
        } else {
            final String[] brightness = new String[]{
                    "settings",
                    "put",
                    "system",
                    "screen_brightness",
                    String.valueOf(level)
            };
            Shell.run(brightness, Shell.User.SHELL);
        }
    }

    public static void writeSysFile(File sysFile, byte[] buffer) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(sysFile);
            fos.write(buffer);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void writeSysFile(String path, byte[] buffer) {
        writeSysFile(new File(path), buffer);
    }

    //配置HDMI显示
    //on:不管有没有插入HDMI都强制显示
    //off:关闭HDMI显示
    //detect:检测到HDMI插入就显示, 否则不显示
    public static void setHdmiDisplay(String action) {
        File root = new File("/sys/class/drm/");
        if (root.exists()) {
            File[] hdmis = root.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File file, String s) {
                    return s.startsWith("card0-HDMI-A-");
                }
            });

            for (File hdmi : hdmis) {
                File status = new File(hdmi.getAbsolutePath() + "/status");
                if (status.exists()) {
                    writeSysFile(status, action.getBytes());
                }
            }
        }
    }


    //设置usb摄像头方向
    public static void setUsbCamera(String name, boolean front, int orientation) {
        int result = Shell.setprop(
                String.format("persist.uvc.%s.capability", TextUtils.isEmpty(name) ? "video" : name),
                String.format("%s-%d", front ? "front" : "back", orientation));
        if (result == 0) {
            Shell.setprop("sys.uvc.reconfigure", System.currentTimeMillis());
        }
    }

    //修改MIPI摄像头旋转方向
    public static void setCifCamera(String name, boolean front, int orientation) {
        int result = Shell.setprop(
                String.format("persist.cif.%s.capability", TextUtils.isEmpty(name) ? "video" : name),
                String.format("%s-%d", front ? "front" : "back", orientation));
        if (result == 0) {
            Shell.setprop("sys.cif.reconfigure", System.currentTimeMillis());
        }
    }

    ////静默安装
    //            Toast.makeText(this,"静默安装中...",Toast.LENGTH_LONG).show();
    //            String path= Environment.getExternalStorageDirectory().getAbsolutePath();
    //            Log.d(TAG,"install_path="+path);
    //            apkInstall(path+"/mount_check.apk");
    //静默安装
    private void apkInstall(String apkFile) {
        new Thread() {
            @Override
            public void run() {
                int result = Shell.run(new String[] {"pm", "install", "-r", "-g", apkFile});
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(getApplicationContext(), String.format("%s安装%s", apkFile, (result == 0) ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
//                    }
//                });
            }
        }.start();
    }

    // 静默卸载
    // Toast.makeText(this,"静默卸载中...",Toast.LENGTH_LONG).show();
    //            apkUninstall("com.lonbon.qianlinmountmaster");

    private void apkUninstall(String packageName) {
        new Thread() {
            @Override
            public void run() {
                int result = Shell.run(new String[] {"pm", "uninstall", packageName});
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(getApplicationContext(), String.format("%s卸载%s", packageName, (result == 0) ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
//                    }
//                });
            }
        }.start();
    }

    //设置背光 HDMI亮度无法控制，能控制MIPI、LVDS、eDP等的屏背光
//            Toast.makeText(this,"关闭HDMI显示",Toast.LENGTH_LONG).show();
    //                setBacklightBrightness(true, 40);
    //配置HDMI显示
    //on:不管有没有插入HDMI都强制显示
    //off:关闭HDMI显示
    //detect:检测到HDMI插入就显示, 否则不显示
    //setHdmiDisplay("on");
//    boolean isHDIMOn = true;
//    if (isHDIMOn){
//        setHdmiDisplay("off");
//        isHDIMOn = false;
//    } else {
//        setHdmiDisplay("on");
//        isHDIMOn = true;
//    }
}

